package xu.htgl.controller;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xu.htgl.common.Result;
import xu.htgl.entity.Account;
import xu.htgl.entity.Admin;
import xu.htgl.service.AdminService;
import xu.htgl.utils.TokenUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping("/selectAll")
    public Result selectAll(Admin admin){
        Result admins = adminService.selectAll(admin);
        return Result.ok(admins);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1")Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       Admin admin
                       ){
        PageInfo page = adminService.page(pageNum, pageSize,admin);
        return Result.ok(page);
    }

    /**
     * 新增管理员
     * @param admin
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Admin admin){
        if (admin.getPassword() != null) {
            admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        }
        Result save =  adminService.save(admin);
        return Result.ok(save);
    }

    /**
     * 修改管理员信息
     * @param admin
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody Admin admin){
        Result update = adminService.updata(admin);
        return Result.ok(update);
    }

    /**
     * 删除管理员信息
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public Result deleteById(Integer id){
        Result delete = adminService.deleteById(id);
        return Result.ok(delete);
    }

    /**
     * 批量删除管理员信息
     * @param ids 要删除的管理员的 id 列表
     * @return 删除结果
     */
    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.failed("未提供要删除的 ID 列表");
        }
        Result result = adminService.batchDelete(ids);
        return result;
    }

    /**
     * 数据导出
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response, Admin admin) throws Exception{
        String ids = admin.getIds();
        if(StrUtil.isNotBlank(ids)){
            String[] split = ids.split(",");
            admin.setIdsArr(split);
        }
        ExcelWriter writer = null;
        ServletOutputStream os = null;
        try {
            // 1. 拿到所有数据
            Result result = adminService.selectAll(admin);
            List<Admin> list = (List<Admin>) result.getData();
            // 2. 构建Writer对象
            writer = ExcelUtil.getWriter(true);
            // 3. 设置中文表头
            writer.addHeaderAlias("username", "账号");
            writer.addHeaderAlias("name", "名称");
            writer.addHeaderAlias("phone", "电话");
            writer.addHeaderAlias("email", "邮箱");
            writer.setOnlyAlias(true);
            // 4. 写出数据到writer
            writer.write(list);
            // 5. 设置输出的文件的名称以及输出流的头信息
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("管理员信息", StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            // 6. 写出到输出流
            os = response.getOutputStream();
            writer.flush(os);
        } catch (Exception e) {
            log.error("数据导出失败", e);
        } finally {
            // 关闭 writer 和输出流
            if (writer != null) {
                writer.close();
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    log.error("关闭输出流失败", e);
                }
            }
        }
    }

    /**
     * 批量导入
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws Exception {
        // 1. 拿到输入流 构建 reader
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 2. 通过Reader 读取 excel 里面的数据
        reader.addHeaderAlias("账号","username" );
        reader.addHeaderAlias("名称","name" );
        reader.addHeaderAlias("电话","phone" );
        reader.addHeaderAlias("邮箱", "email");
        List<Admin> list = reader.readAll(Admin.class);
        // 3. 将数据写到数据库
        for (Admin admin : list) {
            adminService.save(admin);
        }
        return Result.ok();
    }

    /**
     * 单独更新管理员头像
     * @param admin 包含 id 和 avatar 的管理员对象
     * @return 影响的行数
     */
    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestBody Admin admin) {
        // 通常 avatar 为文件上传后的 URL 或路径
        return adminService.updateAvatar(admin);
    }
}
